package com.shengdong.water.code.network.interceptor

import android.content.Context
import android.util.Log
import com.alibaba.android.arouter.facade.Postcard
import com.alibaba.android.arouter.facade.annotation.Interceptor
import com.alibaba.android.arouter.facade.callback.InterceptorCallback
import com.alibaba.android.arouter.facade.template.IInterceptor
import com.shengdong.water.code.config.RouterConfig
import com.shengdong.water.code.config.UserConfig
import com.shengdong.water.code.router.RouterManager


/**
 * 登录拦截器
 * 优先级按照数字大小顺序执行，数字越小，优先级越高
 */

@Interceptor(priority = 8, name = "登录拦截器")
class LoginInterceptor : IInterceptor {

    override fun init(context: Context) {
        // 拦截器初始化

    }


    override fun process(postcard: Postcard, callback: InterceptorCallback) {
        val path = postcard.path

        // 登录页面不需要登录检查
        if (path == RouterConfig.LOGIN_PATH) {
            callback.onContinue(postcard)
            return
        }

        // 需要登录才能访问的页面
        val needLogin = path == RouterConfig.MAIN_PATH
        if (needLogin) {
            // 检查是否已登录
            if (UserConfig.user == null) {
                Log.d("LoginInterceptor", "User not logged in, redirecting to login page")
                // 没有登录，跳转到登录页面
                RouterManager.navigate(RouterConfig.LOGIN_PATH)
                // 拦截当前路由
                callback.onInterrupt(RuntimeException("请先登录"))
            } else {
                Log.d("LoginInterceptor", "User already logged in, continuing navigation")
                // 已登录，继续导航
                callback.onContinue(postcard)
            }
        } else {
            // 不需要登录的页面，直接继续
            callback.onContinue(postcard)
        }
    }

}
